﻿using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Win32;

namespace Quiz_Builder.Controls
{
    /// <summary>
    /// Interaction logic for ImageViewer.xaml
    /// </summary>
    public partial class ImageViewer : UserControl
    {
        public static readonly DependencyProperty ImageProperty =
            DependencyProperty.Register("Image", typeof (IList<byte>), typeof (ImageViewer),
                                        new PropertyMetadata(null, OnImageChanged));

        public ImageViewer()
        {
            InitializeComponent();
        }

        public IList<byte> Image
        {
            get { return (IList<byte>) GetValue(ImageProperty); }
            set { SetValue(ImageProperty, value); }
        }

        private static void OnImageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                var byteStream = new MemoryStream((byte[]) e.NewValue);
                var image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = byteStream;
                image.EndInit();
                ((ImageViewer) d).image.Source = image;
            }
        }

        private void PickImageButtonClick(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog {Filter = "jpg|*.jpg"};
            if (!dlg.ShowDialog().Value)
                return;
            using (Stream file = dlg.OpenFile())
            {
                var buff = new byte[file.Length];
                file.Read(buff, 0, buff.Length);
                Image = buff;
            }
        }
    }
}